// stores/cart.ts
import { defineStore } from 'pinia'
import { cartApi, type CartItem, type CartListResponse } from '@/api/cart'

interface CartState {
  cartList: CartItem[]
  total: number
  selectedTotal: number
  totalPrice: string
  selectedTotalPrice: string
  loading: boolean
  error: string | null
}

export const useCartStore = defineStore('cart', {
  state: (): CartState => ({
    cartList: [],
    total: 0,
    selectedTotal: 0,
    totalPrice: '0',
    selectedTotalPrice: '0',
    loading: false,
    error: null,
  }),

  getters: {
    // 计算选中商品总数
    selectedCount: (state) => {
      return state.cartList.reduce((total, item) => {
        return total + (item.selected == true ? item.goods_num : 0)
      }, 0)
    },

    // 计算选中商品总价
    selectedTotalAmount: (state) => {
      return state.cartList.reduce((total, item) => {
        if (item.selected == true) {
          return total + parseFloat(item.goods_info.goods_price) * item.goods_num
        }
        return total
      }, 0)
    },

    // 检查是否有选中商品
    hasSelectedItems: (state) => {
      return state.cartList.some((item) => item.selected == true)
    },

    // 获取选中商品的ID列表
    selectedCartIds: (state) => {
      return state.cartList.filter((item) => item.selected == true).map((item) => item.cart_id)
    },

    // 获取选中商品列表
    selectedCartItems: (state) => {
      return state.cartList.filter((item) => item.selected == true)
    },
  },

  actions: {
    // 设置加载状态
    setLoading(loading: boolean) {
      this.loading = loading
    },

    // 设置错误信息
    setError(error: string | null) {
      this.error = error
    },

    // 强制刷新计算属性
    forceUpdate() {
      // 通过重新赋值触发响应式更新
      this.cartList = [...this.cartList]
    },

    // 强制更新所有计算属性
    forceUpdateAll() {
      // 触发所有相关计算属性的更新
      this.selectedTotal = this.selectedCount
      this.totalPrice = this.calculateTotalPrice().toString()
      this.selectedTotalPrice = this.selectedTotalAmount.toString()
      this.forceUpdate()
    },

    // 更新购物车数据 - 修复数据映射问题
    updateCartData(data: CartListResponse) {
      this.cartList = data.results || []
      this.total = data.count || 0

      // 重新计算选中相关数据
      this.selectedTotal = this.selectedCount
      this.totalPrice = this.calculateTotalPrice().toString()
      this.selectedTotalPrice = this.selectedTotalAmount.toString()

      // 强制刷新计算属性
      this.forceUpdate()
    },

    // 计算购物车总价
    calculateTotalPrice(): number {
      return this.cartList.reduce((total, item) => {
        return total + parseFloat(item.goods_info.goods_price) * item.goods_num
      }, 0)
    },

    // 获取购物车列表
    async fetchCartList() {
      // 如果已经在加载中，直接返回
      if (this.loading) {
        return this.cartList
      }

      this.setLoading(true)
      this.setError(null)

      try {
        console.log('开始请求购物车数据...')
        const response = await cartApi.getCartList()
        console.log('购物车数据请求成功:', response)

        // 直接使用响应数据，不检查 code（因为 API 响应结构可能不同）
        this.updateCartData(response)
        console.log('购物车数据已保存到Store:', this.cartList)
        return response
      } catch (error: any) {
        console.error('获取购物车数据失败:', error)
        const errorMsg = error.message || '网络错误，请稍后重试'
        this.setError(errorMsg)
        throw error
      } finally {
        this.setLoading(false)
      }
    },

    // 添加商品到购物车
    async addToCart(goods_id: number, goods_num: number) {
      this.setLoading(true)
      this.setError(null)

      try {
        console.log(`添加商品到购物车: goods_id=${goods_id}, goods_num=${goods_num}`)

        // 先更新本地数据，提升响应速度
        const newItem = {
          cart_id: Date.now(), // 临时ID，实际ID会在API响应中返回
          user: 0, // 用户ID会在API响应中更新
          goods: goods_id,
          goods_num: goods_num,
          selected: true,
          goods_info: {
            goods_id: goods_id,
            goods_name: '商品名称',
            goods_price: '0',
            goods_cover_img: '',
            goods_sales: 0,
            goods_stock: 0,
            is_active: true,
          },
          create_time: new Date().toISOString(),
          update_time: new Date().toISOString(),
        }

        // 添加到本地列表
        this.cartList.push(newItem)

        // 更新计算字段
        this.total = this.cartList.length
        this.selectedTotal = this.selectedCount
        this.totalPrice = this.calculateTotalPrice().toString()
        this.selectedTotalPrice = this.selectedTotalAmount.toString()

        // 发送API请求
        const response = await cartApi.addToCart({ goods: goods_id, goods_num })
        console.log('添加购物车成功', response)

        // 用实际API响应更新本地数据
        const itemIndex = this.cartList.findIndex(
          (item) => item.goods === goods_id && item.cart_id === newItem.cart_id,
        )
        if (itemIndex !== -1) {
          // 更新为实际的API响应数据
          this.cartList[itemIndex] = { ...this.cartList[itemIndex], ...response }
        }
      } catch (error: any) {
        console.error('添加商品到购物车失败:', error)
        this.setError(error.message || '添加商品失败')
        throw error
      } finally {
        this.setLoading(false)
      }
    },

    // 更新购物车商品数量 - 修复类型问题
    async updateCartItem(cart_id: number, goods_num: number, selected: 0 | 1) {
      this.setLoading(true)
      this.setError(null)

      try {
        console.log(
          `更新购物车商品: cart_id=${cart_id}, goods_num=${goods_num}, selected=${selected}`,
        )
        await cartApi.updateCartItem(cart_id, { goods_num, selected })
        console.log('更新购物车商品成功')

        // 更新本地数据
        const itemIndex = this.cartList.findIndex((item) => item.cart_id === cart_id)
        if (itemIndex !== -1) {
          this.cartList[itemIndex].goods_num = goods_num
          // 将 selected 转换为 boolean 类型存储
          this.cartList[itemIndex].selected = selected === 1
        }

        // 强制更新所有计算属性
        this.forceUpdateAll()
      } catch (error: any) {
        console.error('更新购物车商品失败:', error)
        this.setError(error.message || '更新商品失败')
        throw error
      } finally {
        this.setLoading(false)
      }
    },

    // 移除购物车商品
    async removeCartItem(cart_id: number) {
      this.setLoading(true)
      this.setError(null)

      try {
        console.log(`移除购物车商品: cart_id=${cart_id}`)
        await cartApi.removeCartItem(cart_id)
        console.log('移除购物车商品成功')

        // 从本地数据中移除
        this.cartList = this.cartList.filter((item) => item.cart_id !== cart_id)

        // 强制更新所有计算属性
        this.forceUpdateAll()
      } catch (error: any) {
        console.error('移除购物车商品失败:', error)
        this.setError(error.message || '移除商品失败')
        throw error
      } finally {
        this.setLoading(false)
      }
    },

    // 批量选中/取消选中 - 修复类型转换
    async batchSelectCartItems(cart_ids: number[], selected: 0 | 1) {
      this.setLoading(true)
      this.setError(null)

      try {
        console.log(`批量选择购物车商品: cart_ids=${cart_ids}, selected=${selected}`)
        await cartApi.batchSelectCartItems({ cart_ids, selected })
        console.log('批量选择成功')

        // 更新本地选中状态
        this.cartList.forEach((item) => {
          if (cart_ids.includes(item.cart_id)) {
            item.selected = selected === 1
          }
        })

        // 更新计算字段
        this.selectedTotal = this.selectedCount
        this.totalPrice = this.calculateTotalPrice().toString()
        this.selectedTotalPrice = this.selectedTotalAmount.toString()

        // 强制刷新计算属性
        this.forceUpdate()
      } catch (error: any) {
        console.error('批量选择购物车商品失败:', error)
        this.setError(error.message || '操作失败')
        throw error
      } finally {
        this.setLoading(false)
      }
    },

    // 清空购物车
    async clearCart() {
      this.setLoading(true)
      this.setError(null)

      try {
        console.log('清空购物车')
        await cartApi.clearCart()
        console.log('清空购物车成功')

        // 重置所有数据
        this.cartList = []
        this.total = 0
        this.selectedTotal = 0
        this.totalPrice = '0'
        this.selectedTotalPrice = '0'
      } catch (error: any) {
        console.error('清空购物车失败:', error)
        this.setError(error.message || '清空购物车失败')
        throw error
      } finally {
        this.setLoading(false)
      }
    },

    // 数量增减
    async updateQuantity(cart_id: number, newQuantity: number) {
      const item = this.cartList.find((item) => item.cart_id === cart_id)
      if (item) {
        // 确保数量不小于1
        const quantity = Math.max(1, newQuantity)
        // 将 boolean 转换为 0 | 1
        const selected = item.selected ? 1 : 0
        await this.updateCartItem(cart_id, quantity, selected)
      }
    },

    // 切换选中状态
    async toggleSelect(cart_id: number) {
      const item = this.cartList.find((item) => item.cart_id === cart_id)
      if (item) {
        const newSelected = item.selected ? 0 : 1
        await this.updateCartItem(cart_id, item.goods_num, newSelected)
      }
    },

    // 检查商品是否在购物车中
    isGoodsInCart(goods_id: number): boolean {
      return this.cartList.some((item) => item.goods === goods_id)
    },

    // 根据商品ID获取购物车项
    getCartItemByGoodsId(goods_id: number): CartItem | undefined {
      return this.cartList.find((item) => item.goods === goods_id)
    },

    // 验证购物车数据
    validateCartData() {
      const errors: string[] = []
      const outOfStockItems: CartItem[] = []
      const inactiveItems: CartItem[] = []

      this.cartList.forEach((item) => {
        if (item.goods_num > item.goods_info.goods_stock) {
          outOfStockItems.push(item)
          errors.push(`商品 "${item.goods_info.goods_name}" 库存不足`)
        }

        if (!item.goods_info.is_active) {
          inactiveItems.push(item)
          errors.push(`商品 "${item.goods_info.goods_name}" 已下架`)
        }
      })

      return {
        isValid: errors.length === 0,
        errors,
        outOfStockItems,
        inactiveItems,
      }
    },

    prepareCheckoutData() {
      const validation = this.validateCartData()
      const validItems = this.selectedCartItems.filter(
        (item) => this.checkStock(item) && item.goods_info.is_active,
      )
      const invalidItems = [...validation.outOfStockItems, ...validation.inactiveItems]

      const totalAmount = this.selectedTotalAmount
      const totalQuantity = this.selectedCount

      return {
        validItems,
        invalidItems,
        totalAmount,
        totalQuantity,
      }
    },

    // 检查商品库存
    checkStock(item: CartItem): boolean {
      return item.goods_num <= item.goods_info.goods_stock && item.goods_info.is_active
    },
  },
})
